import os

import redis
import requests
from loguru import logger
import datetime
import traceback
import json


global_pool = None


def get_redis_conn(db=1):
    redis_info = {
        # "host": f"192.168.1.102",

        #"host": f"10.47.40.243",
        "host": f"192.168.1.73",

        #"port": 6000
        "port": 6379
    }

    global global_pool
    if global_pool is None:
        logger.info(f'创建Redis连接池...')
        global_pool = redis.ConnectionPool(
            max_connections=1000,
            host=redis_info['host'],
            port=redis_info['port'],
            db=db,
            decode_responses = True
        )
    try:
        redis_conn = redis.Redis(connection_pool=global_pool)
        return redis_conn
    except Exception as e:
        logger.error(f"Redis连接失败，{traceback.format_exc()}")
        return None


def save_token_to_file(token):
    end_timestamp = int(datetime.datetime.now().replace(hour=23, minute=59, second=59).timestamp())
    with open(r'D:\ceshi_python\lab\air-conditioning-mpc-component-gitlab\read_data\token.txt', 'w') as f:
        target = {
            'token': token,
            'end_timestamp': end_timestamp
        }
        json.dump(target, f, indent=4)


def fetch_token_to_file():
    # with open(r'D:\ceshi_python\lab\air-conditioning-mpc-component-gitlab\read_data\token.txt', 'r') as f:
    current_dir = os.path.dirname(os.path.abspath(__file__))
    token_file = os.path.join(current_dir, 'token.txt')
    with open(token_file, 'r') as f:
        token_dict = json.load(f)
        if token_dict.get('end_timestamp') > int(datetime.datetime.now().timestamp()):

            return token_dict.get('token')
        else:
            return False


def get_request_head_token():
    redis_conn = get_redis_conn()
    # redis_conn = current_app.config['REDIS_CONN']
    token_key = '__api_header_token_qfc__'

    token = redis_conn.get(token_key)

    # token = fetch_token_to_file()
    # token = False


    # logger.info(token)
    if token:
        #logger.success('获取缓存中的token成功')

        return token
    else:
        # get_url = 'http://10.47.40.243:8200/yunqi/e-server/login'
        #get_url = 'http://192.168.1.102:8200/yunqi/e-server/login'
        get_url = 'http://server.yunhanenergy.com:8200/yunqi/e-server/login'
        #get_url = 'http://manage.yunhanenergy.com:8200/yunqi/e-server/login'

        # get_url = current_app.config['FETCH_DATA_URL'].get('fetch_verify_token_url')

        body_data = {
            "username": "qingfangcheng",
            "password": "qingfangcheng"
        }
        token = requests.post(get_url, json=body_data).json().get('data')
        logger.success('新获取token成功')

        redis_conn.set(token_key, token)

        expiration_timestamp = int(datetime.datetime.now().replace(hour=23, minute=59, second=59).timestamp())
        redis_conn.expireat(token_key, expiration_timestamp)  # 设置过期时间
        # save_token_to_file(token)
        return token


if __name__ == '__main__':
    a = get_request_head_token()
    print(a)


